package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author : Rookie
 * @description : 二叉树左右视图
 * @date : 2023/10/14
 */
public class BinaryTreeView {

    public static void main(String[] args) {
        int[] input = {3, 9, 20, -1, -1, 15, 7};
        TreeNode root = BinaryTreeUtil.buildTree(input);
        getRightView(root);
        getLeftView(root);
    }

    private static void getLeftView(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            // 当前层的节点个数
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
                if (curr != null) {
                    if (i == 0) {
                        result.add(curr.element);
                    }

                    if (curr.left != null) {
                        queue.offer(curr.left);
                    }
                    if (curr.right != null) {
                        queue.offer(curr.right);
                    }
                }
            }
        }
        System.out.println(result);
    }

    private static void getRightView(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<>();

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
                if (curr != null) {
                    if (i == size-1) {
                        list.add(curr.element);
                    }
                    if (curr.left!=null) {
                        queue.offer(curr.left);
                    }
                    if (curr.right != null) {
                        queue.offer(curr.right);
                    }
                }

            }

        }

        System.out.println(list);
    }
}
